package com.cskaoyan.aspectj;

import com.cskaoyan.bean.common.BaseRespVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

/**
 * 处理用valid校验参数，参数不正确时的返回值
 * @author zhuqiushi
 * @since 2022/09/08 11:49
 */
@Aspect
@Component
public class ValidatorHandlerAspectJ {
    @Pointcut("execution(* com.cskaoyan.config..*(..))")
    public void config() {

    }

    @Around("execution(* com.cskaoyan.controller..*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        //从args中取出bindingHandler
        for (Object arg : args) {
            if(arg instanceof BindingResult){
                //在此判断是否通过校验
                BindingResult bindingResult = (BindingResult) arg;
                if (bindingResult.hasErrors()) {
                    //拿到错误
                    FieldError fieldError = bindingResult.getFieldError();
                    //拿到请求参数名
                    String field = fieldError.getField();
                    //获取错误的值
                    Object rejectedValue = fieldError.getRejectedValue();
                    //获取错误信息
                    String defaultMessage = fieldError.getDefaultMessage();
                    StringBuffer sb = new StringBuffer();
                    String msg = sb.append("请求参数")
                            .append(field)
                            .append("传入的值")
                            .append(rejectedValue)
                            .append("有问题 : ")
                            .append(defaultMessage).toString();
                    return BaseRespVo.invalidParameter(msg);
                }
            }
        }
        //如果值没问题，等其他情况继续执行方法
        Object proceed = joinPoint.proceed();
        return proceed;
    }
}
